/* Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.yzbdl.lanius.orchestrate.utils;

import com.baomidou.mybatisplus.annotation.TableName;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;
import org.yzbdl.lanius.orchestrate.common.base.entity.BaseOrgEntity;
import org.yzbdl.lanius.orchestrate.common.base.entity.IdOrgFieldEntity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 用来获取哪些entity包含了orgid
 *
 * @author chenjunhao
 * @date 2022-04-11 13:24
 */
public class OrgHelperUtil {

	/**
	 * 扫描包地址
	 */
	private static final String ENTITY_SCAN = "org.yzbdl.lanius.orchestrate.serv.entity";
	public static List<String> ORG_TABLE_NAMES = new ArrayList<>();

	/**
	 * 扫描并记录带有orgId的表名称
	 */
	public static void setOwnerOrgIdTableNames(){
		ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
		try{
			String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(ENTITY_SCAN)+"/**/*.class";
			Resource[] resources = resourcePatternResolver.getResources(pattern);
			MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
			for(Resource resource :resources){
				MetadataReader reader = readerFactory.getMetadataReader(resource);
				String className = reader.getClassMetadata().getClassName();
				Class<?> clazz = Class.forName(className);
				TableName tableName = clazz.getAnnotation(TableName.class);
				if(tableName!=null){
					Class<?> cls = clazz.getSuperclass();
					if(cls.equals(BaseOrgEntity.class)||cls.equals(IdOrgFieldEntity.class)){
						ORG_TABLE_NAMES.add(tableName.value());
					}
				}
			}
		}catch (IOException | ClassNotFoundException ignored){}
	}

	/**
	 * 获取表名
	 * @return 表名列表
	 */
	public static List<String> getOrgTableNames(){
		if(ORG_TABLE_NAMES.size()==0){
			setOwnerOrgIdTableNames();
		}
		return ORG_TABLE_NAMES;
	}
}
